/**
 * 楼盘地图
 * Created by douxc on 2015/4/24.
 */
define(function (require, exports, module) {
  'use strict';
  module.exports = function (app) {
    app.register.controller('BuildingCtrl', ['$scope', 'MHService','$location',function ($scope, MHService,$location) {
      MHService.cacheData(true, {key: 'map', value: 'true'});



      /**
       * 百度地图相关常量
       */
      //var DEFAULT_MARKER = new BMap.Icon("../app/images/marker.png", new BMap.Size(27, 70));
      var CURRENT_MARKER = new BMap.Icon("./images/ic_current_location.png", new BMap.Size(25, 54));
      //初始化地图，默认点为天安门
      var map = new BMap.Map("bMap");    // 创建Map实例
      map.centerAndZoom(new BMap.Point(118.789572, 32.048667), 13);  // 初始化地图,设置中心点坐标和地图级别
      //map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
      //map.setCurrentCity("南京");          // 设置地图显示的城市 此项是必须设置的
      // 添加带有定位的导航控件
      var navigationControl = new BMap.NavigationControl({
        // 靠左上角位置
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
        // LARGE类型
        type: BMAP_NAVIGATION_CONTROL_ZOOM,
        offset: new BMap.Size(10, 35)
      });
      map.addControl(navigationControl);

        //如果这个这个对象存在就更换坐标
        var cityid,tempUrl;
        if(MHService.globalData(false, {key: 'city'})){
            var address = MHService.globalData(false, {key: 'city'}).name;
            $scope.cityName = address;//设置城市名
                cityid = MHService.globalData(false, {key: 'city'}).id;
            // 创建地址解析器实例
            var myGeo = new BMap.Geocoder();
            // 将地址解析结果显示在地图上，并调整地图视野
            myGeo.getPoint(address, function(point){
                if (point) {
                    map.centerAndZoom(new BMap.Point(point.lng, point.lat), 13);
                    tempUrl = MHService.URL.buildings + "?lng=" + point["lng"] + "&lat=" + point["lat"];
                }
            });
        }else{
            $scope.cityName = "选择";//默认城市名
        }


      /**
       * 在地图上画出兴趣点,并添加点击事件
       * @param points
       */
      var drawPoints = function (points) {
//          console.log('55',points);
        //把兴趣点画在地图上
        for (var i = 0, len = points.length; i < len; i++) {
          var markerObj = points[i], lat, lng;
          if (markerObj['latlng']) {
            lat = markerObj['latlng'].split(',')[0];
            lng = markerObj['latlng'].split(',')[1];
          } else {
            continue;
          }
          var point = new BMap.Point(lng, lat);
          var marker = new BMap.Marker(point);
          //marker.setIcon(DEFAULT_MARKER);
          //console.log(marker);
          map.addOverlay(marker);
          addClickHandler(markerObj, marker);
        }
        var markerPoint = null;//marker点的位置坐标
        var lastmarker = null;//上一次点击的marker
        function addClickHandler(markerObj, marker) {
          marker.addEventListener("click", function (e) {
            var lat = markerObj['latlng'].split(',')[0],
              lng = markerObj['latlng'].split(',')[1];
            markerPoint = new BMap.Point(lng, lat);
            map.panTo(markerPoint);
            if (lastmarker != null) {
              //如果不是第一次点击，则先将上一个marker图标重置
              //lastmarker.setIcon(DEFAULT_MARKER);
            }
            //marker.setIcon(CURRENT_MARKER);
            lastmarker = marker;
            //显示详情
            $scope.$apply(function () {
              $scope.currentMarker = markerObj;
              $scope.showBottom = true;
              console.info(markerObj);
            });
            //保存当前点击的marker
            MHService.setCurrentMarker(markerObj);
          });
        };
      };//drawPoints end
      /**
       * 请求附近的楼盘
       */
      var queryNearByGasStation = function (point) {
//        var gasurl = MHService.URL.buildings + "?lng=" + point["lng"] + "&lat=" + point["lat"];
          var gasurl = MHService.URL.estate + "?cityid=" + cityid;//该城市的楼盘
        MHService.getReq({url: gasurl}, function (data) {
          drawPoints(data["datas"]);
        });
      };
      MHService.queryLocation(function (point) {
        var mk = new BMap.Marker(point);
        mk.setIcon(CURRENT_MARKER);
        map.addOverlay(mk);
        map.panTo(point);
        map.setZoom(14);
        queryNearByGasStation(point);
      });

        //选择城市
        $scope.changeCity = function(){
            $location.path("selectCity");
        }

        //请求附近的楼盘
        $scope.queryNear = function(){
            map.clearOverlays();    //清楚百度地图上的坐标点
//            console.log("tempUrl="+tempUrl);
            MHService.getReq({url: tempUrl}, function (data) {
//                console.log('97',data);
                drawPoints(data["datas"]);
            });
        }
    }]);
  };
});
